using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Sql;
using System.Data.SqlClient;
using Saiket.CommonInfo;
using Saiket.BLL;

public partial class Blog : System.Web.UI.Page
{

   public string siteDirName = System.Configuration.ConfigurationManager.AppSettings["siteDirName"].ToString();
   string extension = System.Configuration.ConfigurationManager.AppSettings["extension"].ToString();
    
    
    
    public string getGeneratedScript(string permaLink, object titleObj, string publisher)
    {
        string generated = "<script type=\"text/javascript\">\n";
        generated += "  addthis_url    = '" + permaLink+"';\n";
        generated += "  addthis_title  = '" + titleObj.ToString() + "';\n";
        generated += "  addthis_pub    = '"+publisher+"';\n";
        generated += "</script><script type=\"text/javascript\" src=\"http://s7.addthis.com/js/addthis_widget.php?v=12\" ></script>\n";
        return generated;
    }
        
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.MaintainScrollPositionOnPostBack = true;
        Calendar1.ToolTip = "Calender is given to find out the lates post easily.\r\n User The BLog Archive tree for all posts";

        BusinessLogicLayer bll = new BusinessLogicLayer();
        lblCloudTagsLinks.Text = bll.GetColudedTagsLinks();
        

              //  TreeView1.ExpandAll();
            Page.Title = Application["BlogTitle"].ToString();
            if (Request.Params["tagname"] != null)
            {
                if (!IsPostBack)
                {
                    try
                    {
                        TreeView1.ExpandAll();
                        string tagname = Request.Params["tagname"].ToString();
                        string command = @"SELECT BlogID,
                                        PostTitle,
                                        REPLACE(PostTitle, ' ', '-') AS PostTitleLinks, 
                                        PostContent,
                                        PostDate, 
                                        DAY(PostDate) AS date,
                                        MONTH(PostDate) AS month,
                                        YEAR(PostDate) AS year,
                                        PostedBy,
                                        PostCaption,
                                        PostTags,
                                        (SELECT COUNT(commentID) AS Expr1 FROM BlogComment WHERE (Blog.BlogID = BlogID)) AS CommentCount FROM Blog
                                         WHERE (PostTags LIKE @tagname) order by PostDate desc; ";

                        SqlDataSource1.SelectCommand = command;
                        SqlDataSource1.SelectParameters.Add("tagname", "%"+tagname+"%");
                        DataList1.DataBind();
                        
                        ///////////////////
                        /*
                         * Setting dynamic title
                         */
                        /////////////////////////

                        SqlCommand sc = new SqlCommand();
                        sc.CommandText = command;
                        sc.Parameters.AddWithValue("tagname", "%" + tagname + "%");
                        string title = "::" + CommonInfo.GetBasicTitle() + " | Blog | " + RunQuery(sc).Tables[0].Rows[0]["PostTags"].ToString() + "::";
                        Page.Title = title;
                        ////////////////////////
                        SqlDataSource1.Dispose();

                        // commentLink
                    }
                    catch (Exception ex)
                    { 
                    
                    }
                

                }
            
            }

            if (Request.Params["blogid"] == null)
            {

            }
            else
            {
                
                if (!IsPostBack)
                {
                    try
                    {
                        TreeView1.ExpandAll();
                        string blogid = Request.Params["blogid"].ToString();
                        string command = @"SELECT BlogID,
                                        PostTitle,
                                        REPLACE(PostTitle, ' ', '-') AS PostTitleLinks, 
                                        PostContent,
                                        PostDate, 
                                        DAY(PostDate) AS date,
                                        MONTH(PostDate) AS month,
                                        YEAR(PostDate) AS year,
                                        PostedBy,
                                        PostCaption,
                                        PostTags,
                                        (SELECT COUNT(commentID) AS Expr1 FROM BlogComment WHERE (Blog.BlogID = BlogID)) AS CommentCount FROM Blog
                                        where BlogID = @BlogID";
                       
                        SqlDataSource1.SelectCommand = command;
                        SqlDataSource1.SelectParameters.Add("BlogID", blogid);
                        DataList1.DataBind();
                        ///////////////////
                        /*
                         * Setting dynamic title
                         */
                        /////////////////////////

                        SqlCommand sc= new SqlCommand();
                        sc.CommandText = command;
                        sc.Parameters.AddWithValue("BlogID", blogid);
                        string title = "::" + CommonInfo.GetBasicTitle() + " | Blog | " + RunQuery(sc).Tables[0].Rows[0]["PostTitle"].ToString() + "::";
                        Page.Title = title;
                        ////////////////////////
                        SqlDataSource1.Dispose();

                       // commentLink
                        
                    }
                    catch
                    { 
                    
                    }
                }
          
            }
   


    }
    
    protected void tvwBlogArchive_TreeNodePopulate(object sender, TreeNodeEventArgs e)
    {
        ////////

       
            if (e.Node.ChildNodes.Count == 0)
            {
                switch (e.Node.Depth)
                {
                    case 0:
                        PopulateYears(e.Node);
                        break;
                    case 1:
                        PopulateMonths(e.Node);
                        break;
                    case 2:
                        PopulateBlogPosts(e.Node);
                        break;
                }
            }
        

     
        ////////////
    }
    
    #region Blog Tree Generation Functions


    void PopulateYears(TreeNode node)
    {
        SqlCommand sqlQuery = new SqlCommand(
            "SELECT DISTINCT CAST(YEAR(PostDate) AS VARCHAR(4)) AS Year " +
            "FROM Blog " +
            "ORDER BY Year DESC");
        DataSet resultSet;
        resultSet = RunQuery(sqlQuery);
        if (resultSet.Tables.Count > 0)
        {
            foreach (DataRow row in resultSet.Tables[0].Rows)
            {
                TreeNode NewNode = new TreeNode(row["Year"].ToString());
                NewNode.PopulateOnDemand = true;
                //NewNode.Expanded = false;
                NewNode.SelectAction = TreeNodeSelectAction.Expand;
                node.ChildNodes.Add(NewNode);

               
            }
        }
    }


    void PopulateMonths(TreeNode node)
    {
        SqlCommand sqlQuery = new SqlCommand();
        sqlQuery.CommandText = "SELECT DISTINCT CAST(MONTH(PostDate) AS int) AS Month " +
        "FROM Blog " +
        "WHERE CAST(YEAR(PostDate) AS VARCHAR(4)) = @Year " +
        "ORDER BY Month DESC";
        sqlQuery.Parameters.Add("@Year", SqlDbType.Int).Value = node.Value;
        DataSet ResultSet = RunQuery(sqlQuery);
        if (ResultSet.Tables.Count > 0)
        {
            foreach (DataRow row in ResultSet.Tables[0].Rows)
            {
                //, "",siteDirName+"Blog/Blog.html", "_self"
                string MonthUrl = siteDirName + "Blog/Blog" + extension;
                TreeNode NewNode = new TreeNode(Utility.GetMonthName(row["Month"].ToString()), row["Month"].ToString() + "-" + node.Value, "", MonthUrl, "_self");
                NewNode.PopulateOnDemand = true;
                NewNode.SelectAction = TreeNodeSelectAction.SelectExpand;
                node.ChildNodes.Add(NewNode);
            }
        }
    }

    void PopulateBlogPosts(TreeNode node)
    {
        SqlCommand sqlQuery = new SqlCommand();
        sqlQuery.CommandText = "SELECT BlogID,DAY(postDate) as date, PostTitle " +
        "FROM Blog " +
        "WHERE CAST(YEAR(PostDate) AS VARCHAR(4)) = @Year AND  " +
        "CAST(MONTH(PostDate) AS VARCHAR(2)) = @Month " +
        "ORDER BY PostDate DESC";

        int month = Utility.Left(node.Value, node.Value.IndexOf("-"));
        int year = Utility.Right(node.Value, node.Value.IndexOf("-"));

        sqlQuery.Parameters.Add("@Month", SqlDbType.Int).Value = month;
        sqlQuery.Parameters.Add("@Year", SqlDbType.Int).Value = year;

        DataSet ResultSet = RunQuery(sqlQuery);
        if (ResultSet.Tables.Count > 0)
        {
            foreach (DataRow row in ResultSet.Tables[0].Rows)
            {
                string date = row["date"].ToString();
                string blogDynaUrl = @"" + siteDirName + "Blog/" + month + "/" + date + "/" + year + "/" + row["BlogID"] + "/" + Utility.titleReplace(row["PostTitle"].ToString()) + extension;
                TreeNode NewNode = new TreeNode(row["PostTitle"].ToString(), row["BlogID"].ToString(), "", blogDynaUrl, "_self");
                NewNode.PopulateOnDemand = false;
                NewNode.SelectAction = TreeNodeSelectAction.SelectExpand;
                node.ChildNodes.Add(NewNode);
                blogDynaUrl = null;
            }
        }
    } 
    #endregion

    private DataSet RunQuery(SqlCommand sqlQuery)
    {
        string connectionString = ConfigurationManager.ConnectionStrings["Personal"].ConnectionString.ToString();
        SqlConnection DBConnection = new SqlConnection(connectionString);
        SqlDataAdapter dbAdapter = new SqlDataAdapter();
        dbAdapter.SelectCommand = sqlQuery;
        sqlQuery.Connection = DBConnection;
        DataSet resultsDataSet = new DataSet();
        try
        {
            dbAdapter.Fill(resultsDataSet);
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message.ToString();
        }
        finally
        {
            DBConnection.Close();
        }
        return resultsDataSet;
    }

    protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
    {

        HtmlInputHidden title = (HtmlInputHidden)e.Item.FindControl("title");
        HtmlInputHidden permaLinkData = (HtmlInputHidden)e.Item.FindControl("permaLink");
        HtmlInputHidden publisher = (HtmlInputHidden)e.Item.FindControl("publisher");
        string permaLinkMain = "http://www.saiket.com/" + "Blog/" + permaLinkData.Value + extension;
        Label lblBookmark = (Label)e.Item.FindControl("bookmark");
        lblBookmark.Text = getGeneratedScript(permaLinkMain, title.Value, publisher.Value);

    }

    protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {
        

        Hashtable schedule = new Hashtable();
       //schedule["2/23/2008"] = "Last day of Chanukah";
       //schedule["2/24/2008"] = "Christmas Eve";
       //schedule["2/25/2008"] = "Christmas"+"ok and ok";;
       
       
        ///////////////



        string command = @"SELECT BlogID, PostTitle,
                                        REPLACE(PostTitle, ' ', '-') AS PostTitleLinks, 
                                        PostContent,
                                        PostDate, 
                                        DAY(PostDate) AS date,
                                        MONTH(PostDate) AS month, 
                                        YEAR(PostDate) AS year,
                                        PostedBy,
                                        PostCaption,
                                        PostTags, 
                                        (SELECT COUNT(commentID) AS Expr1 FROM BlogComment WHERE (Blog.BlogID = BlogID)) AS CommentCount
                                        FROM Blog";

        SqlCommand sqlQuery = new SqlCommand(command);
        DataSet resultSet;
        resultSet = RunQuery(sqlQuery);

        if (resultSet.Tables.Count > 0)
        {

            foreach (DataRow row in resultSet.Tables[0].Rows)
            {
                string date = row["date"].ToString();
                string month = row["month"].ToString();
                string year = row["year"].ToString();

                string schDate = month + "/" + date + "/" + year;
                schedule[schDate] = row["PostTitle"];
            }
        }

        //if (e.Day.IsSelected)
        //{
        //    DateTime selectedDateTime = Calendar1.SelectedDate;
        //   int day = selectedDateTime.Day;
        //   int month = selectedDateTime.Month;
        //   int year = selectedDateTime.Year;
        //    //   Response.Redirect("http://localhost/saiket/Blog/9/11/2007/9/Gale-hat-dia-boisa-ase.aspx);
        //}


        if (schedule[e.Day.Date.ToShortDateString()] != null)
        {
            string blogTitle = (string)schedule[e.Day.Date.ToShortDateString()];
            e.Cell.ForeColor = System.Drawing.Color.DarkBlue;
            e.Cell.Font.Bold = true;
            e.Day.IsSelectable = true;
            e.Cell.Attributes.Add("onmouseover", "javascript:Tip('" + blogTitle + "',SHADOW, true,PADDING, 1,ABOVE,true,LEFT,true,FADEIN, 1000,FADEOUT, 1000)");
  

        }
        else
        {
            e.Day.IsSelectable = false;
        }
    }
    protected void C(object sender, EventArgs e)
    {

    }
}


class Utility
{
    public static string titleReplace(string oldTitle)
    {
        return oldTitle.Replace(" ", "-");
    }

    public static int Left(string nodeValue, int separatorpos)
    {
        int leftInt = 0;
        string leftString = nodeValue.Substring(0, separatorpos);
        leftInt = Int32.Parse(leftString);
        return leftInt; //  Utility.Left(node.Value, node.Value.IndexOf("-"));
    }
    public static int Right(string nodeValue, int separatorpos)
    {
        int leftInt = 0;
        string leftString = nodeValue.Substring(separatorpos + 1, (nodeValue.Length - (separatorpos + 1)));
        leftInt = Int32.Parse(leftString);
        return leftInt; //  Utility.Left(node.Value, node.Value.IndexOf("-"));
    }
    public static string GetMonthName(string monthCode)
    {
        int intMonthCode = Int32.Parse(monthCode);
        string[] months ={ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

        return months[intMonthCode - 1].ToString();
    }

}